<template>
    <view class="payment">
        <!-- Header Start -->
        <view class="header flex flex-col justify-center items-center">
            <price
                :content="price"
                mainSize="44rpx"
                minorSize="34rpx"
                fontWeight="500"
                color="#ffffff"
                :prec="3"
            ></price>
            <view
                class="flex justify-center text-white mt-[20rpx] font-xs"
                v-if="payment.cancelTime >= 0 && payment.orderType != PayEnum.RECHARGE"
            >
                <text class="mr-[10rpx]">请在</text>
                <u-count-down
                    :timestamp="payment.cancelTime"
                    @end="handleCountDownEnd"
                    format="mm:ss"
                    :font-size="22"
                />
                <text class="ml-[10rpx]">内进行支付</text>
            </view>
        </view>
        <!-- Header End -->

        <!-- Main Start -->
        <view class="main bg-white">
            <!--优惠券-->
            <view
                class="coupon flex p-[30rpx] justify-between"
                style="border-bottom: 1px solid #f6f6f6"
                @click="couponPop = true"
                v-if="payment.orderType != PayEnum.RECHARGE"
            >
                <view>优惠券</view>
                <view class="flex" v-if="isUseCoupon == ''">
                    <view class="mr-[10rpx]" v-if="!couponData.avaliable.data.length"
                        >暂无可用的优惠券</view
                    >
                    <view class="mr-[10rpx]" v-else>{{
                        `${couponData.avaliable.data.length || '无'}张优惠券可用`
                    }}</view>
                    <u-icon name="arrow-right" color="#666666" size="28"></u-icon>
                </view>
                <view class="flex" v-if="isUseCoupon != ''">
                    <view class="mr-[10rpx] text-[#FA8919]">{{ `-¥${isUseCoupon.amount}` }}</view>
                    <u-icon name="arrow-right" color="#666666" size="28"></u-icon>
                </view>
            </view>
            <!--积分抵扣-->
            <view
                class="coupon flex p-[30rpx] justify-between"
                style="border-bottom: 1px solid #f6f6f6"
                v-if="payment.orderType != PayEnum.RECHARGE && integralConfig.enable == '1'"
            >
                <view>积分抵扣</view>
                <view class="flex items-center">
                    <view class="text-muted" v-if="!integralConfig.isDeductible"
                        >共{{ integralConfig.userPoints }}积分，满{{
                            integralConfig.lowerLimit
                        }}可用</view
                    >
                    <view class="flex" v-if="integralConfig.isDeductible">
                        <view class="muted"
                            >共{{ integralConfig.userPoints }}积分，已使用{{
                                integralConfig.usedPoints
                            }}积分抵</view
                        >
                        <view class="text-[#FA8919]"> ¥{{ integralConfig.deductibleAmount }}</view>
                    </view>
                    <u-checkbox
                        class="ml-[10rpx]"
                        :disabled="!integralConfig.isDeductible"
                        @change="integralCheckBoxChange"
                        v-model="isSelectIntegral"
                        active-color="#FA8919"
                    ></u-checkbox>
                    <!-- <view class="flex">
                        <view class="text-[#FA8919]">{{ `-¥${isUseCoupon.amount}` }}</view>
                    </view> -->
                </view>
            </view>
            <view class="title">支付方式</view>
            <!-- 支付方式 -->
            <view class="payway">
                <view
                    class="payway-item"
                    v-for="(item, index) in payment.payWayLists"
                    @click="selectPayWay(item.payId)"
                    :key="index"
                >
                    <image class="payway-item--icon" :src="item.payImage"></image>
                    <view class="payway-item--name flex-1">{{ item.payName }}</view>
                    <view class="payway-item--select">
                        <image
                            v-if="payWay === item.payId"
                            src="/static/images/icon_select.png"
                        ></image>
                    </view>
                </view>
            </view>

            <view class="submit-btn">
                <u-button
                    @click="handlePlaceOrder"
                    :ripple="true"
                    shape="circle"
                    :hair-line="false"
                    type="primary"
                    throttle-time="1000"
                    >立即支付</u-button
                >
            </view>
        </view>
        <!--绑定微信弹框-->
        <u-popup v-model="bindwx" mode="center" borderRadius="14" :mask-close-able="false">
            <view class="course-pop text-center">
                <view class="text-lg font-medium normal pt-[45rpx] pb-[40rpx]"
                    >抱歉，您还未绑定微信</view
                >
                <view class="flex justify-between mt-[60rpx]">
                    <u-button
                        @click="goPage('/pages/user_set/user_set')"
                        class="flex-1"
                        :ripple="true"
                        shape="circle"
                        :hair-line="false"
                        type="primary"
                        >去绑定</u-button
                    >
                    <u-button
                        @click="bindwx = false"
                        class="flex-1 m-l-30"
                        :ripple="true"
                        shape="circle"
                        :hair-line="false"
                        type="gary"
                        >取消</u-button
                    >
                </view>
            </view>
        </u-popup>

        <!--优惠券弹框-->
        <u-popup
            v-model="couponPop"
            mode="bottom"
            height="850rpx"
            borderRadius="14"
            safe-area-inset-bottom
            closeable
        >
            <view class="px-[30rpx]">
                <view class="title py-[25rpx] h-[100rpx] text-center text-3xl sticky top-0 bg-white"
                    >优惠</view
                >
                <view>
                    <tabs :isScroll="false" :current="current" height="80" :showBar="false">
                        <tab
                            v-for="(value, key, index) in couponData"
                            :key="index"
                            :name="`${value.name}(${value.data.length})`"
                        >
                            <view class="tabH">
                                <scroll-view scroll-y class="h-full">
                                    <view
                                        v-for="(item, index1) in value.data"
                                        :key="index1"
                                        class="py-[15rpx]"
                                        @click="selectCoupon(item, index)"
                                    >
                                        <coupon-card
                                            :is-select-coupon="
                                                isSelectCoupon.receiveId == item.receiveId
                                            "
                                            :disabled="index == 1"
                                            :coupon-data="item"
                                            :type="2"
                                        ></coupon-card>
                                    </view>
                                    <view
                                        v-if="value.data.length == 0"
                                        class="flex flex-col items-center justify-center h-full"
                                    >
                                        <image
                                            src="@/static/images/empty/collection.png"
                                            class="w-[200rpx] h-[200rpx]"
                                        >
                                        </image>
                                        <view>暂无数据～</view>
                                    </view>
                                </scroll-view>
                            </view>
                        </tab>
                    </tabs>
                </view>
                <view class="h-[100rpx]">
                    <button class="bg-primary rounded-[100rpx] text-white" @click="confirm">
                        确定
                    </button>
                </view>
            </view>
        </u-popup>

        <!-- Main End -->

        <skeleton v-if="loading"></skeleton>
    </view>
</template>

<script lang="ts" setup>
import { ref, watch, nextTick, computed } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { getClient, toast } from '@/utils/util'
import Price from '@/components/price/index.vue'
import skeleton from './components/skeleton.vue'
import { usePay } from '@/hooks/payment'
import { useUserStore } from '@/stores/user'
import { ClientEnum, PayEnum, PayWayEnum } from '@/utils/enum'
import Tabs from '@/components/tabs/tabs.vue'
import couponCard from '@/components/coupon-card/index.vue'
import { avaliableCoupon, unavaliableCoupon } from '@/api/coupon'
import { getSignInSet } from '@/api/signIn'

/** Data Start **/
const useAppStore = useUserStore()
const bindwx = ref(false)
// 支付方式
const payWay = ref<number>(0)
// 支付钩子
const { loading, initPay, handlePayPrepay, payment, handlePayResult } = usePay()
// 优惠券弹框
const couponPop = ref<boolean>(false)
//被选中优惠券
const isSelectCoupon = ref<any>('')
//使用优惠券
const isUseCoupon = ref<any>('')
//价格
const price: any = ref<string | number>(0)
//不渲染的价格
const statePrice: any = ref(0)
//积分选择
const isSelectIntegral = ref(true)

//积分配置
const integralConfig: any = ref({
    enable: '1',
    isDeductible: '', //是否可用积分抵扣
    userPoints: '', //用户总积分
    usedPoints: '', //本次交易可用积分
    deductibleAmount: '', //本次交易可抵扣金额
    lowerLimit: '' //积分使用下限
})

//优惠券数据
const couponData: any = ref({
    avaliable: {
        name: '可用优惠券',
        data: []
    },
    unavaliable: {
        name: '不可用优惠券',
        data: []
    }
})

const current = ref(0)

/** Data End **/

/** Watch Start **/
// 监听支付方式，默认为第一位支付
watch(
    () => payment.payWayLists,
    (value) => {
        //payWay.value = value[0]?.payId
        payWay.value = value.find((item) => item.isDefault == 1).payId
    }
)
/** Watch End **/

/** Methods Start **/
//选择支付方式
const selectPayWay = (payway: number) => {
    payWay.value = payway
}

//支付
const handlePlaceOrder = () => {
    if (price.value == 0 && payWay.value == PayWayEnum.WECHAT) {
        toast('支付金额为0，请选择余额支付！')
        return
    }
    if (
        payWay.value == 1 &&
        useAppStore.$state.userInfo.isBindMnp == false &&
        getClient() != ClientEnum.H5
    ) {
        bindwx.value = true
        return
    }
    try {
        // 预支付
        if (isSelectIntegral.value) {
            handlePayPrepay(
                payWay.value,
                isUseCoupon.value.amount,
                isUseCoupon.value.receiveId,
                integralConfig.value.deductibleAmount,
                integralConfig.value.usedPoints
            )
            return
        }
        handlePayPrepay(payWay.value, isUseCoupon.value.amount, isUseCoupon.value.receiveId)
    } catch (err) {
        console.log('预支付调用', err)
    }
}

//倒计时结束
const handleCountDownEnd = async (): Promise<void> => {
    await uni.showModal({
        title: '温馨提示',
        showCancel: false,
        content: '当前订单支付时间已过，请重新下单',
        success: () => {
            uni.navigateBack()
        }
    })
}

//获取优惠券列表
const getCouponList = async () => {
    if (payment.orderType == PayEnum.RECHARGE) return
    couponData.value.unavaliable.data = await unavaliableCoupon({
        orderId: payment.order_id,
        amount: payment.orderAmount
    })
    couponData.value.avaliable.data = await avaliableCoupon({
        orderId: payment.order_id,
        amount: payment.orderAmount
    })
}

//默认选中第一张优惠券
const selectFirst = () => {
    if (couponData.value.avaliable.data.length == 0) return
    try {
        selectCoupon(couponData.value.avaliable.data[0], 0)
        confirm()
    } catch (error) {
        console.log(error)
    }
}

//选择优惠券
const selectCoupon = (value: any, index: any) => {
    //index 0-可用优惠券 1-不可用优惠券
    if (index == 1) return
    if (isSelectCoupon.value.receiveId == value.receiveId) {
        isSelectCoupon.value = ''
        return
    }
    isSelectCoupon.value = value
}

//优惠券确认
const confirm = async () => {
    isUseCoupon.value = isSelectCoupon.value
    await nextTick()
    await countPrice()
    couponPop.value = false
    getSignInconfig()
}

//积分checkbox
const integralCheckBoxChange = async ({ value }: any) => {
    await nextTick()
    countPrice()
}
//计算价格
const countPrice = () => {
    price.value = payment.orderAmount
    if (isSelectCoupon.value && isSelectIntegral.value) {
        price.value =
            price.value -
            Number(isUseCoupon.value.amount) -
            Number(integralConfig.value.deductibleAmount)
        price.value < 0 ? (price.value = 0) : ''
    } else if (isSelectCoupon.value && !isSelectIntegral.value) {
        price.value = price.value - Number(isUseCoupon.value.amount)
        price.value < 0 ? (price.value = 0) : ''
    } else if (!isSelectCoupon.value && isSelectIntegral.value) {
        price.value = price.value - Number(integralConfig.value.deductibleAmount)
        price.value < 0 ? (price.value = 0) : ''
    }
}

//获取积分配置
const getSignInconfig = async () => {
    let res: any
    if (!isSelectCoupon.value) {
        res = await getSignInSet({ orderPrice: statePrice.value })
    } else {
        res = await getSignInSet({
            orderPrice: statePrice.value - Number(isUseCoupon.value.amount)
        })
    }
    Object.keys(integralConfig.value).map((item) => {
        integralConfig.value[item] = res[item]
    })
    countPrice()
}

// 跳转页面方法
const goPage = (url: string) => {
    uni.navigateTo({
        url: url
    })
}
/** Methods End **/

/** Life Cycle Start **/
onLoad(async (options: any) => {
    console.log(options)
    //h5支付确定弹框
    if (options.showPop == '1') {
        uni.showModal({
            title: '提示',
            content: '请确认是否已支付',
            success: function (res) {
                if (res.confirm)
                    uni.reLaunch({
                        url: `/bundle/pages/pay_result/index?orderId=${payment.order_id}`
                    })
                else if (res.cancel)
                    uni.reLaunch({
                        url: `/bundle/pages/order_detail/index?id=${payment.order_id}`
                    })
            }
        })
    }
    // 初始化支付方式
    await nextTick()
    await initPay(options.orderData)
    price.value = payment.orderAmount
    statePrice.value = payment.orderAmount
    if (payment.orderType == PayEnum.ORDER) {
        await getCouponList()
        await getSignInconfig()
        selectFirst()
    }
})

onUnload(() => {
    handlePayResult()
})
/** Life Cycle End **/
</script>

<style lang="scss">
.payment {
    background: linear-gradient(to bottom, $color-primary 500rpx, transparent 0);

    .header {
        height: 200rpx;
        padding: 40rpx 0;
        text-align: center;
    }

    .main {
        border-radius: 20rpx 20rpx 0 0;
        height: calc(100vh - 200rpx - env(safe-area-inset-bottom));

        .title {
            color: $color-text-muted;
            font-size: $font-size-sm;
            padding: 30rpx 0 20rpx 30rpx;
        }

        .payway {
            .payway-item {
                padding: 24rpx;
                display: flex;
                justify-content: space-between;
                border-bottom: 1px solid $color-bg;

                &--icon {
                    width: 40rpx;
                    height: 40rpx;
                }

                &--name {
                    color: $color-text-deep;
                    font-size: $font-size-lg;
                    margin-left: 24rpx;
                }

                &--select {
                    width: 36rpx;
                    height: 36rpx;

                    image {
                        width: 100%;
                        height: 100%;
                    }
                }
            }
        }

        .submit-btn {
            padding: 0 24rpx;
            margin-top: 60rpx;
        }
    }
}

// 通用弹窗
.course-pop {
    width: 640rpx;
    padding: 70rpx 80rpx 40rpx 80rpx;
}

.tabH {
    height: calc(850rpx - 280rpx - env(safe-area-inset-bottom));
}

::v-deep .u-checkbox {
    display: block !important;
}
</style>
